Utils.register("Cnbi.model");
/**
 * 公式静态类
 * @type 
 */
Cnbi.model.Constant={
       PERCENTCONTENT:'PERCENT',//此常量表示查询记录是否有百分数
       INDEX:'index0',
       DRILL:0,
       MAPDRILL:0,
       HASMAP:false,
       HASMONTH:true,
       TIME:"201210",
       TEMPWIDTH:1005,
       dupont:'dupont',
       assets:'assets'

};
/**
 * 基于fushioncharts封装的通用类  可以不依赖任何脚本框架运行
 * @param {} params={
 *   		chartType:2,
            swfName:"Pie2D",
            datas:[{},[{},{}]] ,
            domId:"test"
 *  }
 *   new Cnbi.model.Chart({
 *     chartType:1,
 *     swfName:'Pie2D',
 *     datas:[{},{},{}],
 *     domId:'pie1',
 *     width:"100%",
       heigth:"90%",
       attributes:showLabels:1
 *   }).init();
 */
//
Cnbi.model.Chart=function(bean){
	 if(arguments.length==0){console.info("亲，您未传入参数！"); return;};
	 CnbiSoft.setCurrentRenderer('JavaScript');
	  var defaults = {
            styles:{
					"definition" : [{
								"name" : "captionStyle",
								"font" : "微软雅黑",
								"size" : "13",
								"bgColor" : "FFFFDD",
								"color" : "000"
							}],
					"application" : [{
								"toobject" : "caption",
								"styles" : "captionStyle"
							}]
	        },
	        chart:{
				    "bgcolor" : "FFFFFF",
					"palette" : "2",
					"showvalues" : "1",
					"showborder" : "1",
					"exportenabled" : "1",
					"formatnumber" : "1",
					"formatnumberscale" : "0",
					"forcedecimals" : "1",
					"decimals" : "2",
					 borderColor:'dddddd'
		  },angleChart: {},
    "colorrange": {
        "color": [
            {
                "minvalue": "0",
                "maxvalue": "45",
                "code": "FF654F"
            },
            {
                "minvalue": "45",
                "maxvalue": "80",
                "code": "F6BD0F"
            },
            {
                "minvalue": "80",
                "maxvalue": "100",
                "code": "8BBA00"
            }
        ]
    },
    "dials": {
        "dial": [
            {
                "value": "72",
                "rearextension": "10",
                "basewidth": "10"
            }
        ]
    },
    "trendpoints": {
        "point": [
            {
                "startvalue": "62",
                "displayvalue": "Average",
                "usemarker": "1",
                "markerradius": "8",
                "dashed": "1",
                "dashlen": "2",
                "dashgap": "2"
            }
        ]
    },
    "annotations": {
        "groups": [
            {
                "id": "Grp1",
                "showbelow": "1",
                "showshadow": "1",
                "items": [
                    {
                        "type": "rectangle",
                        "x": "$chartStartX+5",
                        "y": "$chartStartY+5",
                        "tox": "$chartEndX-5",
                        "toy": "$chartEndY-5",
                        "radius": "10",
                        "fillcolor": "009999,333333",
                        "showborder": "0"
                    }
                ]
            }
        ]
    },
    "styles": {
        "definition": [
            {
                "name": "RectShadow",
                "type": "shadow",
                "strength": "3"
            },
            {
                "name": "trendvaluefont",
                "type": "font",
                "bold": "1",
                "bordercolor": "FFFFDD"
            }
        ],
        "application": [
            {
                "toobject": "Grp1",
                "styles": "RectShadow"
            },
            {
                "toobject": "Trendvalues",
                "styles": "trendvaluefont"
            }
        ]
    }

        };
        Utils.applyIf(defaults,bean);//把所有params变量的所有属性都 给defaults私有变量
		function getSingleSeriesData(bean){
			var data = [];
			for(var i=0 ,len = bean["value"].length;i<len;i++){
				var label = bean["label"][i],value = bean["value"][i],
				obj = {label:label,value:value,tooltext:label+value};
				if(bean["color"])obj["color"] = bean["color"][i]
			    data.push(obj);
			}
			if(bean["chart"])Utils.applyIf(defaults.chart,bean["chart"]);
			if(bean["styles"])Utils.applyIf(defaults.styles,bean["styles"]);
			return {chart:defaults["chart"],styles:defaults["styles"],data:data};

		}
		function getChart(bean){
		    var chartId = bean["swf"] + "chartId", myChart = {};
			if (CnbiSoft(chartId)) {
				myChart = CnbiSoft(chartId);
			} else {
				myChart = new CnbiSoft("/resources/charts/swf/"+ bean["swf"] + ".swf", chartId, "100%","100%","0");
			}
			return myChart;
		}
	     this.createSingleSeriesChart=function() {
				var chartData = getSingleSeriesData(bean),
				myChart = getChart(bean);
				myChart.setJSONData(chartData);//chart.view2D();
				myChart.render(bean["domId"]);
		 }
			function getChartAttr(bean){
				return $("#"+bean["domId"]).attrFusionCharts(bean.attr)
			}
			function changeChartTheme(bean){//D977B7
			   $("#"+bean["domId"]).attrFusionCharts({"palette": bean["palette"], "paletteColors": bean["paletteColors"]});
			}
			function updateChart(bean){
				if(!bean["type"]) bean["type"] = "json";
			     $("#"+bean["domId"]).updateFusionCharts({dataSource: bean["data"], dataFormat:bean["type"]});
			}
			this.createAngleChart=function() {
				var myChart = getChart(bean);
				 // myChart.setJSONData(defaults["angleChart"]);//chart.view2D();
					/*myChart.setXMLData('<chart lowerLimit="0" upperLimit="100" lowerLimitDisplay="Bad" upperLimitDisplay="Good" numberSuffix="%" showValue="1">\n\
							<colorRange>\n\
							<color minValue="0" maxValue="75" code="FF654F"/>\n\
							<color minValue="75" maxValue="90" code="F6BD0F"/>\n\
							<color minValue="90" maxValue="100" code="8BBA00"/>\n\
							</colorRange>\n\
							<dials>\n\
							<dial value="92" />\n\
							</dials>\n\
							</chart>');*/
				myChart.setXMLUrl("../resources/xml/angle.xml");
				myChart.render(bean["domId"]);
		 }
			/**
			 * Print Page
			 */
			function printPage (){
			    CnbiSoft.printManager.managedPrint()
			}
       this.init=function(){};
    
	   this.init();
}
/**
 * 系统模型公共抽象类   data: { json: JSON.stringify({"name": "someValue"}) }, JSON.parse(b);
 * @param {} params
 */
Cnbi.model.BaseSliderAndProgress=function(params){
     this.defaults = {
       	params:{query:3,month:'03月份', year:'2012', unit:'亿元'},
       	url:Utils.getBasePathUrl() + "compose/dashboard.cnbi"
    };
    var Ids={vaprefix:"cnbi",dupont:"dupont",assets:"assets"}
    this.debug=false;
    this.vaprefix=Ids["vaprefix"];
    this.hasCache=false;
    Utils.initDate();
    Utils.applyIf(this.defaults,params);//把所有params变量的所有属性都 给defaults私有变量
    var scope = this,//类本身
     reg = new RegExp(",","g");//正则表达式对象
    scope.datas={};//数据对象
    scope.flag=false;//对象只new一次！其它操作均为更新操作的判断变量
    this.industyParams={};
    var index_key="";//缓存键key
    this.module = this.defaults["module"];//模型对象
    this.itemIndex= this.module["queryItemScode"];//传入数据库查询item参数对象
    this.toolsMap = module["toolsMap"];//帮助map
     if(this.module["formulas"]["db_formulas"]){
      this.indi = this.module["formulas"]["db_formulas"];//数据库公式对象
    }
     if(this.module["formulas"]["userDefined_formulas"]){
        this.zIndicator =this.module["formulas"]["userDefined_formulas"];//自定义公式对象
    }
    if(this.module["formulas"]["assists_formulas"]){
        this.assistsFormulas =this.module["formulas"]["assists_formulas"];//辅助公式对象
    }
    if(this.module["repalceVar"]){
        this.repalceVar =this.module["repalceVar"].split(",");//需要替换变量的对象
    }
    this.initDomValue=function(id, value){
 	  if(isNaN(value)||value==Infinity){
			value =  0.00;
		}
	 	var f = Utils.millon(Utils.formatFloat(value, 2));
	 	if(id.indexOf("span")==-1){
	 		$("#" + id).val(f);//如果不是span节点
	 	}else{
	 	   $("#" + id).text(f);//是span节点
	 	}
		$("#" + id).css("color", value < 0 ? "red" : "green");
    };
    this.progressValue =function(a, values) {
		/*if(a == undefined || a == null) return;
		if(typeof a.minValue === undefined){
		  alert();
		  return;
		}*/
		var min = a.minValue, max = a.maxValue, value = 0;
		// alert(min+"--"+min)
		if (values > 0) {
			value = 0.5 + values / (2 * max);
			if (value > 1) {
				value = 1;
			}
		}
		if (values == 0) {
			value = 0.5;
			if (min == 0) {
				value = 0;
			}
		}
		if (values < 0) {
			value = 0.5 - Math.abs(values / (2 * min));
			if (value < 0)
				value = 0;
		}
		return value;
	}
    /**
     * 全局datas设值  
     * 设置datas全局数据对象
     */
    this.setBodyData=function (data){
    	 var obj ={};
    	try{
    	     	obj = Ext.decode(data);
    	     	if(obj instanceof Array){
    	     	      scope.datas =obj[1];
    	     	}else{
    	     	    scope.datas =obj ;
    	     	}
    	     	if(scope.debug) console.info(scope.datas);
    	      	Utils.setLocalStorage(index_key,encodeURIComponent(data));
    	}catch(e){//var msg = data.replace(/^[u4E00-u9FA5]+$/,data);
    		//var msg = data.split(">")[1];
    		//msg = msg.substring(0,msg.length-5);
    		//var msg = data.replace(/[^\u4E00-\u9FA5]/g,'');
    	  //  alert("查询出错了:"+e);
    	    this.onFailure();
    	    return;
    	}    
     
         for(var xx in scope.datas){
        	 scope.datas[xx] = scope.datas[xx]-0;
        }
     //   console.info(scope.datas);
        this.defaultsInit();
    }
    /**
     * 执行辅助公式 倒减时最有用
     */
    this.initBefore=function(){
    	if(!this.assistsFormulas)return; //	alert("执行辅助公式 倒减时最有用!");
	 	var fomu = this.assistsFormulas;
	      for(var i=0;i<fomu.length;i++){
		           var o = {id:0,vaprefix:scope.vaprefix,datas:scope.datas};
		            scope.getDefinedIndicatorObjResult(o,fomu[i]);
		            scope.datas[fomu[i]["scode"]] = o.result;
			}
    };
    /**
     * 成功失败都执行的方法
     */
    this.defaultsInit=function(){
    	 this.initBefore();
    	 if(scope.flag==false){
    	 	var sobj=false,pobj=false;
    	 	if(scope.defaults["sli"]){
    	 	    sobj = scope.defaults["sli"];
    	 	}
    	 	if(scope.defaults["pro"]){
    	 	    pobj = scope.defaults["pro"];
    	 	}
          	scope.createSlider(scope.defaults["slider_array"],scope.datas,sobj,scope.defaults["updateInput"]);
	        scope.createProgress(scope.defaults["progress_array"],scope.datas,pobj);
	        scope.initSliderEvent(scope.defaults["slider_array"],scope.datas);
	        scope.setFormula();
	        scope.initInputEvent();
        }
         scope.initPage(); 
         scope.flag=true; 
         setTimeout(function(){
         	//alert(jQuery);
            jQuery("body > div").eq(1).unmask();
         },250);
      //   window.$ = jQuery;
    }
   
    /**
     * 注册input--change事件  console.info($(this).attr("id")+"---"+ $(this).text()+$(this).val())  
     */
    this.initInputEvent=function(){
         $("input").bind("change", function(event){
		 	 labelChange(this);
		});
		 $("input").focus(function(obj){
				var val = this.value.replace(reg,"");
				$(this).val(val);
		});
    }
    /**
     * input响应change事件执行的方法
     */
	function labelChange(obj){
	  	var inputFlag = scope.defaults["updateInput"];
		var newValue = obj.value.replace(reg, "") - 0,
		deaultValue = eval(obj.id.replace(inputFlag,"")),
		slider = Ext.getCmp((obj.id).replace(inputFlag, "")),
		min = slider.minValue/100,
		max = slider.maxValue/100,
		value = slider.getValue()/100;
		if(Math.abs(value*100 - deaultValue) >=0.5){
			deaultValue =value;
		}
		if (isNaN(newValue)) {
			alert("填写数据有误!只能是数字!请重新输入!");
			obj.focus();
			$(obj).val(Utils.formatFloat(value,2).toFixed(2));
			return false;
		} else if (newValue < min) {
			alert("填写数据小于最小值,输入范围应在[" + min + "-" + max + "]之间!请重新输入!")
			obj.focus();
			$(obj).val(Utils.formatFloat(value,2).toFixed(2));
			return false;
		} else if (newValue > max) {
			alert("填写数据大于最大值,输入范围应在[" + min + "~" + max + "]之间!请重新输入!")
			obj.focus();
			$(obj).val(Utils.formatFloat(value,2).toFixed(2));
			return false;
		}else{
			 newValue = Utils.formatFloat(newValue,2).toFixed(2) - 0;
			 slider.setValue(newValue*100)
			scope.initDomValue(obj.id, newValue);
			 scope.updateInputValue(obj.id,newValue,scope.datas);
		}
			return true;	
};
    /**

     * 从后台响应成功执行的方法 
     */
    this.onSuccess=function(res){
    	console.info(res);

    	if(res=="sessionOut" || res == ""){   
			alert("由于长时间未操作,空闲会话已超时或者数据为NULL了！;！");
		    //window.location.replace(url+"login.jsp");  
		    return;
		}
    	try{
    		//alert(scope.defaults["id"]);
    	    scope.setBodyData(res);
    	    $("#content").slideDown("slow");
    	}catch(e){//$("p")
    		 $("#content").unmask();
    	     alert("您所选择的期间与公司没有数据！");
    	 //   $("#content").slideUp("slow");
    	}    
    	    
          
    };
    /**
     * 从后台响应失败执行的方法 
     */
    this.onFailure=function(res){
    	// alert("数据库查询失败！当前为演示数据！");
         scope.initData();
         scope.defaultsInit();
    };
   /**
    * 绑定维度期间查询事件
    */
    this.bindChangeCondition= function(){
    	//$("body >div ").eq(0).css("background-color", "#fff");
    	//$("body >div ").eq(1).css("background-color", "#fff");
    	var e = "#year,#month,#company,#unit";
    	if(!scope.defaults["params"]["compareYear"]){
    	    $("#compareYear").parent().remove();
    	    $("#compareMonth").parent().remove();
    	}else{
    	   e+=",#compareYear,#compareMonth";
    	  $("#compareYear").val(scope.defaults["params"]["compareYear"]);
    	   $("#compareMonth").val(scope.defaults["params"]["compareMonth"]);
    	 //  scope.defaults["params"]["compareYear"] = $("#compareYear").val();
    	 //  scope.defaults["params"]["compareMonth"] = $("#compareMonth").val();
    	   $("select").width(90);
    	}
    	//console.info(scope.defaults["params"]["year"]+"--------"+scope.defaults["params"]["month"]+""+scope.defaults["params"]["compareYear"]+"--------"+scope.defaults["params"]["compareMonth"]);
    	$("#year").val(scope.defaults["params"]["year"]);
    	$("#month").val(scope.defaults["params"]["month"]);
    //	alert($("#year").val()+"---------"+$("#month").val());
    	$("#company").val(scope.defaults["params"]["company"]);
    	//scope.defaults["params"]["year"] = $("#year").val();
    	//scope.defaults["params"]["month"] = $("#month").val();
    	 $("#unit").val(scope.defaults["params"]["unit"]);
        $(e).change(function(){
        	//console.info(scope.defaults["params"]);
        var id = $(this).attr("id"),val =$(this).val() ;
        scope.defaults["params"][id] =val ;
       // console.info(scope.defaults["params"]);
        scope.init();
	   });
	   $(".cnbi-collapse").click(function(){
			var obj = $(".cnbi-panel-content:first");
			obj.toggle();
			if(obj.is(":hidden")){
				$(this).prop("class","cnbi-collapse cnbi-open").prop("title","单击打开");
				
			}else{
				$(this).prop("class","cnbi-collapse cnbi-close").prop("title","单击隐藏");
			}
		});
    }
    /**
     * 获取查询参数的方法
     */
    this.getParams=function(index){
     	 	var period = $("#year").val()+$("#month").val();
        var params={
        		type:scope.defaults["params"]["type"],
        		povitdim:scope.defaults["params"]["povitDim"],
        		showdim:scope.defaults["params"]["showDim"],
        		queryfact:scope.defaults["params"]["queryFact"],
        		subject:"0001",
        		period:period,
        		company:scope.defaults["params"]["company"]};
         params["item"] =scope.itemIndex;
        return params;
     };
       /**
     * 子类初始默认执行的方法 
     */
    this.init=function(){
    	if(scope.flag==false){
    	  this.bindChangeCondition();
    	  if(this.module["industry"]){
    	     this.getNewIndustry(this.module["industry"]);//industry 
    	 }	
    	}
    	 var params = this.getParams();
    	//console.info($("div").eq(1).attr("class"));
    		//$("#content").mask("正在努力为您加载数据，请稍候......");
    //	alert($("#content").attr("class"));
    	$("#content").mask("正在努力为您加载数据，请稍候......");
    		
    		//alert("company.id===="+scope.defaults["url"]+scope.defaults["params"]["company"]["id"]+scope.defaults["params"]["year"]+scope.defaults["params"]["month"]+scope.defaults["params"]["unit"]+ scope.defaults["params"]["query"]);
    	 var ttemp = scope.defaults["url"]+params["company"]+params["period"]+scope.defaults["params"]["type"];
    	
    	if(scope.defaults["params"]["compareYear"]){
    		//scope.defaults["params"]["year"] = $("#year").val();
    	//scope.defaults["params"]["month"] = $("#month").val();
    	   ttemp+=scope.defaults["params"]["compareYear"]+scope.defaults["params"]["compareMonth"];
    	}
    	//console.info(ttemp);
    	index_key=encodeURIComponent(ttemp);
    	 var cacheData = Utils.getLocalStorage(index_key); 
    //	console.info(this.module["datas"]);
    	 if(this.module["datas"]){
    	       scope.setBodyData(decodeURIComponent(this.module["datas"])); 
	     	  $("#content").slideDown("slow");
    	 }else{
    	 	if(scope.debug==false && cacheData==null){
    	 	     $.ajax({
					url : scope.defaults["url"],
					data : params,
					//dataType: "json",
					type:"POST",
					success :scope.onSuccess ,
					fail :scope.onFailure
					});
		     }else{
		    	 if(cacheData=="null"){
		    		 scope.onFailure();
		    		 return;
		    	 }
		     	  scope.setBodyData(decodeURIComponent(cacheData)); 
		     	  $("#content").slideDown("slow");
		     	 
		     }
    	 }     
         	
     // scope.onFailure();
    };
    
  
   
     /**
     * 子类要实现的初始页面的方法
     */
    this.initPage=function(){
       alert("进父亲了！initPage");
    }
     
    /**
     * 单个Slider组件注册事件组件Id  
     */
    this.initEventEveryOne=function (id,datas){
    	if(id==null || id=="") return;
            var obj = Ext.getCmp(id) ;
            obj.addListener("dragend", function() {
                scope.updateInputValue(id,obj.getValue()/100,datas);
            }, this);
            obj.addListener("changecomplete", function() {
                scope.updateInputValue(id,obj.getValue()/100,datas);
                scope.initChart(false,id);
            }, this);
            obj.addListener("change", function() {
                scope.updateInputValue(id,obj.getValue()/100,datas);
            }, this);  
    };
    /**
     * 实例响应(changecomplete)事件后独有的创建dashboard的行为
     */
     this.initChart=function(action,id){}	
     /**
     * 初始事件所有
     */
      this.initSliderEvent=function(slider_array,datas){
       for (var i = 0; i < slider_array.length; i++) {
         this.initEventEveryOne(slider_array[i]+"",datas);
       }
    };
     /**
     *  实例响应(dragend,changecomplete,change)等3个事件后独有的行为
     */
    this.updataInputAfter=function(){
     };
   /**
      * 执行所有公式
      */
     this.setFormula=function(){ 
     	  var o = {id:0,vaprefix:scope.vaprefix,datas:scope.datas};
     	 if(scope.indi){
			for(var i=0;i<scope.indi.length;i++){
				var id = scope.indi[i]["scode"];
				  o["id"] = id.replaceAll(o["vaprefix"],"");
				scope.getIndicatorResult(o);
			}
     	 }
     	 if(scope.zIndicator){
		   scope.exceteDefinedFormula(o);
     	  }
    }
    /**
     * 响应slider(change,dragend,changecomplete)等3个事件
     */
     this.updateInputValue=function(id ,value,datas ){
     	/* if(this.defaults["doubleUIFlag"]!=undefined){
     	 	if(id.indexOf(this.defaults["doubleUIFlag"])!=-1){
     	 	   var len = id.length;	//console.info("before-----"+id);
        	 	id =id.substring(0,len-this.defaults["doubleUIFlag"].length);
        	 	//console.info("after-----"+id);
     	 	}
          }*/
         scope.datas[id] =  value;
         if(isNaN(value)||value==Infinity){
			value =  0.00;
			console.info("updateInputValue----------"+id+"-------------"+scope.datas[id]+"不是数据！请仔细检查！");
			//return;
		}
        scope.initDomValue(id+this.defaults["updateInput"], value);
        this.setFormula();
        this.updataInputAfter(id ,value,datas );
     };
      /**
     * 创建 Slider        //  alert(typeof datas[array[i]])
     */
     
   this.createSlider=function(array,datas,obj) {
   	  // console.info(datas);alert
   	try{  
   	var width=120;
     	if(obj){width=obj.width;}
        for (var i = 0; i < array.length; i++) {
        	if(array[i]==null || array[i]=="")return;
        	 var valueTemp =this.getValue(array[i]);
      if(this.debug)console.info(i+"-----createSlider------------"+array[i]+"=========="+valueTemp);
        	if(Ids["dupont"]==this.module["id"]){
     		   if(array[i]==this.toolsMap["yysr"]["scode"]||array[i]==this.toolsMap["sds"]["scode"]){
     		   		width=this.defaults["sli"]["width2"];
     		   }else{
     		     width=obj.width;
     		   }
     		}
     		if(!Ext.getCmp(array[i]))
        	new Ext.Slider({
                        renderTo : array[i] + "Id",
                        id : array[i],
                        anchor : '100%', // useTips : false,
                        increment : 1,
                       // width:width,
                        minValue : -1000000, //  clickToChange:true,   //允许单击改变进度值          
                        maxValue : 10000000,
                        value:valueTemp*100
                    });
          //scope.initDomValue(array[i] +flag,datas[array[i]]);
              //console.info(array[i]+"--------------------"+10000);      
        }
    }catch(e){
	      alert("创建 Slider出错！请检查dom的Id书写是否规范！\n"+e);
	      return ;
	}   
    };
    var minMax = getMinMax(scope.defaults["params"]["unit"]);
    /**
     * 获取最大最小值
     */
     function getMinMax(unit){
         if(unit==1) return  10000000;
         if(unit==2)return  1000000;
         if(unit==3) return 100000;
         if(unit==4) return 10000;
    };
     /**
     * 创建 Ext.ProgressBar  doubleUIFlag
     */
     this.createProgress=function(array,datas,obj){
     	/*var id = "Id";
     	if(this.defaults[" doubleUIFlag"]!=undefined){
     	   id = this.defaults[" doubleUIFlag"];
     	}*/
     	 // alert("----createProgress  id==---------"+id);
     	var width=120,height=16;
     	if(obj){ width=obj.width;height=obj.height;}
   			//try{  
        for (var i = 0; i < array.length; i++) {
        	/*if(this.defaults["doubleUIFlag"]!=undefined){
        		if(i<10){
        		  	var len =array[i].length, bj = array[i].substring(0,len-3);
        			console.info("createProgress-----"+i+"----"+array[i]+"=========="+bj+"----"+datas[bj]);
        		}else{
        		    console.info("createProgress-----"+i+"------"+array[i]+"=========---");
        		}
     		}*/
       if(this.debug)console.info("createProgress-----"+i+"------"+array[i]+"=========---");
          var obj = Ext.getCmp(array[i]);
          if(!obj)
        obj = new Ext.ProgressBar({
                        renderTo : array[i].toString() +"Id",
                        id : array[i],
                        width : width,
                        height:height,
                    //  value : 0.6,
                        cls : 'progressBar',
                        minValue : -100 * minMax,
                        maxValue : 100 * minMax
             });
               obj.updateProgress(0.5, false);
              }
   			/*}catch(e){
   			     alert("创建ProgressBar出错！请检查dom的Id书写是否规范！\n"+e);
   			     return;
   			} */  
    };
    /**
     * 设置所有Progress的值
     */
     this.setProgressValue=function(progress_array,datas,flag) {
        var obj = null, value = 0.00;
        for (var i = 0; i < progress_array.length; i++) {
        		if(progress_array[i]==null || progress_array[i]=="") return;
            obj = Ext.getCmp(progress_array[i]);
           var valueTemp =this.getValue(progress_array[i]);
            value = scope.progressValue(obj,valueTemp);
           
            obj.updateProgress(value, false);
           scope.initDomValue(progress_array[i]+flag,valueTemp);
            this.updateProgressClass(obj,valueTemp);
        }
    };
    /**
     * 设置所有Slider的值
     */
     this.setSliderValue=function(slider_array,datas,flag){
     //	var fs = this.defaults["doubleUIFlag"];
        for (var i = 0; i < slider_array.length; i++) {// slider.setValue(index,newValue, false);
        	if(slider_array[i]==null || slider_array[i]=="") return;
        	//slider_array[i] = slider_array[i].replaceAll(fs,"");
        	var valueTemp =this.getValue(slider_array[i]);
           	Ext.getCmp(slider_array[i]).setValue(valueTemp*100,true);
           scope.initDomValue(slider_array[i] +flag,valueTemp);
        }
    };
    /**
     * 根据传来的Id从全局数据对象里获取数据 
     */
     this.getValue=function(array){
    	var valueTemp=0.00;
      if(array.indexOf(this.defaults["doubleUIFlag"])==-1){
              valueTemp = scope.datas[array];
       }else{
          if(this.defaults["doubleUIFlag"]!=undefined){
          var len =array.length, bj =array.split(this.defaults["doubleUIFlag"])[0];
     	  valueTemp =scope.datas[bj];
           }
       }
      // console.info("getValue----"+array+"---"+valueTemp);
       return valueTemp;
    
    }
      /**
     * 默认初始数据 生成m~n之间的随机数： Math.floor(Math.random()*n)+m 如果查询失败！再到localStore里找不到  刚执行此方法
     */
     this.getRandom=function(){
         return (Math.floor(Math.random() * minMax*100) +100)/100
     }
   /**
    * 当查询失败或调试时用的初始随机数据的方法
    */
    this.initData = function() {
    	var flag = this.defaults["doubleUIFlag"];
    	// this.initDataBefore();
    	//alert(minMax+"")
        for (var i = 0; i <  this.defaults["slider_array"].length; i++) {//100--100000
        	var tval = this.getRandom();
            scope.datas[this.defaults["slider_array"][i]] =tval;
           // console.info(this.defaults["slider_array"][i]+"----"+tval);
        	
        }
        for (var i = 0; i < this.defaults["progress_array"].length; i++) {
            // scope.datas[this.defaults["progress_array"][i]] = this.getRandom();
        	var id = this.defaults["progress_array"][i];
        	if(flag && id.indexOf(flag)!=-1){
        	    id = id.split(flag)[0];
        	}
        	var tval = this.getRandom();
         scope.datas[id] = tval;
          //console.info(id+"----"+tval);
        }
        if(scope.debug)console.info(scope.datas);
        if(this.defaults["params"]["itemIndex"]){
            var tempIn = this.defaults["params"]["itemIndex"].split(";");
            if(tempIn.length>1){
                  for (var i = 0; i < tempIn.length; i++) {
                  	        var nzs = tempIn[i].split(",");
                  	     for (var j = 0; j < nzs.length; j++) {
                  	          	var tval = this.getRandom();
                  	          	nzs[j] = nzs[j].replaceAll(flag,"");
                                 scope.datas[nzs[j]] = tval;
                                 if(this.debug)console.info("--------------initData-------------"+nzs[j]+"----"+tval);
                  	     }
                  }
                  
                  
            }
        	  
        }
    }
   
    /**
     * params  @str  Id_span
     * params  val
     * 更新 progress,更新progress对应的dom与span
     */
     this.updataSpanAndProgess=function(str,val){
     	var temp = str.split("_"),id = temp[0],des = temp[0]+temp[1];
     	if(!isNaN(id)){
     	   if(this.debug)console.info("有误的执行，但程序强行把"+id+"转成了"+this.vaprefix+id);
     	   id = this.vaprefix+id;
     	}
     	var obj = Ext.getCmp(id),value =0.00;
     	if(!obj){
     	   if(this.debug)console.info("根据"+id+"没有找到Progess对象！"); return;
     	}
     	if(!val){
     		 value =this.getValue(id);//gjx
      	if(isNaN(value)||value==Infinity){
			throw ("updataSpanAndProgess----------"+id+"-------------"+value+"不是数字 ！请仔细检查！");
			value =  0.00;
			return;
		}
     	}else{
     	  value = val;
     	}
     	if(Ids["dupont"]==this.module["id"]){
     	   if(id== this.toolsMap["qtysk"]["scode"]) return;
     	}
		obj.updateProgress(scope.progressValue(obj,value),false);
		this.initDomValue(des,value);
		this.updateProgressClass(obj,value);
    };
    /**
     * 根据值大小更新progress
     */
     this.updateProgressClass=function(obj,value){
        if(value>0){
        	obj.removeClass("red-progressBar");
			obj.addClass("progressBar");
		}else{
			obj.removeClass("progressBar");
		  	obj.addClass("red-progressBar");
		}
		$(".x-progress-bar").css("height","18px");
     }
    /** 
     * 更新panel头部，已弃用
     */
    this.updataTitle=function(msg){
    	if(Ext.select(".mainshell")){
    		 Ext.select(".mainshell").first().update(msg+"---"+this.defaults["companyName"]);
    	}
    	 	
     
    } 
    /**
     * 根据指标ID获取数据库指标对象 并有变量替换
     * { "expid": "77",
		"sfunction": "Fact('0001','${company},0&0,1114','A')",
		"sexpression": "(((主营业务收入-主营业务成本+主营业务税金及附加+销售费用+管理费用+财务费用-所得税)/主营业务收入)*(主营业务收入/((期末资产总计+年初资产总计)/2))*100)*(1/(1-负债总额/期末资产总计*100))",
		"sparameters": "主营业务收入-主营业务成本-主营业务税金及附加-销售费用-管理费用-财务费用-所得税-期末资产总计-年初资产总计-负债总额",
		"sname": "净资产收益率1",
		"sparameter": "主营业务成本",
		"nindex": "343"
		},
		{
		"id": "1",
		"nindex": "2",
		"sexpression": "主营业务收入/(销量/5)",
		"sfunction": "Fact(\"0001\",\"${company},0&0,1_1150\",\"A\")",
		"sname": "单项销售额",
		"sparameter": "销量",
		"sparameters": "销量-主营业务收入"
   },
     */
     this.getIndicatorBean=function(id,array){
       var temp = [],exp="",name=""; var select_fact=[];
       for (var i = 0; i < array.length; i++) {
       	    if(array[i]["id"].toString()==id){
       	    	exp = array[i]["sexpression"];	name = array[i]["sname"];
       	    	var fun = array[i]["sfunction"], len = fun.length,
       	    	   fact =fun.substring(5,len-1);
       	    	   fact = eval("["+fact+"]");
       	    	   var  dim = fact[1].split(",");
       	    	   var scode = dim[dim.length-1];
       	    	   if(this.repalceVar)
       	    	   for(var x=0;x< this.repalceVar.length;x++){
       	    	   	 var tems = this.repalceVar[x].split("_");
       	    	   	 if(scode==tems[0]){
       	    	   	     scode=tems[1];
       	    	   	     if(this.debug && this.flag==false)console.info("-------var ------------------成功把变量【"+tems[0]+"】替换成了【"+tems[1]+"】");
       	    	   	 }
       	    	   }
       	           temp.push({scode:scode,sname:array[i]["sparameter"],fun:fun,result:fact});
       	           var ts = fact[fact.length-1];
					 for(var j=0;j<select_fact.length;j++){
					    if(ts==select_fact[j]){
					            select_fact.remove(j);
					    }
					  }
					   select_fact.push(ts);
       	    }
       }
      var obj={id:id,name:name,exp:exp,params:temp,col:select_fact};
       return obj;
    };
    /**
     * calculate 计算的地方
     */
     this.afterResult=function(o){
     	try{ 
     		o["result"]=0.00;
     		o["exp"] = o["exp"].replaceAll("--","");//
     		/*if(o["exp"].indexOf("\\")!=-1){
     		  alert(o["id"]+"--"+o["name"]+"--"+o["exp"]);
     		  var dd = o["exp"].replaceAll("--","");
     		  alert(dd);
     		}*/
     		//if(o["id"]=="cnbi75") alert(o["exp"]);
            var r =eval("("+o["exp"]+")")-0,//resultExp = exp+"=="+r,
	        result = Utils.formatFloat(r,2);
	        if(isNaN(result) || result == Infinity||result == -Infinity) result=0.00;
	        //if(isFinite(result)){alert("这个结果是Finite!!!")};
	        if(o["id"].indexOf(o["vaprefix"])==-1){
	           scope.datas[o["vaprefix"]+o["id"]] = result;
	        }else{
	        	 scope.datas[o["id"]] = result;
	        }
	         o["datas"] =  scope.datas;
	         o["result"] = result;
	         if(this.debug)console.info(o["id"]+"----->"+o["namne"]+"----->"+o["exp"]);
	         return o;
     	     }catch(er){
        	     console.error( o["name"]+o["id"]+"-->执行公式操作时出错：-->"+o["oldExp"]+"-->"+o["expCode"]+"-->"+o["exp"]+"-->"+er);
        	    return ;
        }  
    }
    /**
     * 根据传来的指标ID获取结果对象，并把计算出来的值设到全局数据对象里！！！
     */
    this.getIndicatorResult=function(o){
        var vaprefix=o["vaprefix"];
        var data= o["datas"];
     	var bean =this.getIndicatorBean(o["id"],indicator);
     	if(bean["name"]==""|| bean["name"]==null){ 
     	    console.error("错误的Id【"+o["id"]+"】传递,请检查【"+this.module.title+"】模型对应文件夹下的配制文件----》");
     	return;
     	}
       try{ 
	            var	exp  = bean["exp"],exp1 = exp,expCode=exp,
	        	 params = bean["params"];
		           for(var i=0;i<params.length;i++){
		           	var  val = "data."+vaprefix+params[i]["scode"];
		           	var tempResult=eval("("+val+")");
			           	if(typeof tempResult=='undefined'){
			           	      throw "模型实例的数据对象里没有定义数据变量----【"+val+"】----请检查【"+this.module.title+"】模型对应文件夹下的配制文件----》"; //console.info(val+"===="+eval("("+val+")"));
			           	      break;
			           	}else{
			                exp= exp.replaceAll(params[i]["sname"],tempResult);
			               // exp = exp.replace(/"+params[i]["sname"]+"/g, tempResult)
			                expCode= expCode.replaceAll(params[i]["sname"],params[i]["scode"]);
			           	}
		           }
		         o["exp"] = exp;
		         o["name"] = bean["name"];
		         o["oldExp"] = exp1;
		         o["expCode"] = expCode;
		         if(this.debug) console.info(o);
		         this.afterResult(o);
		        /* if(o["id"]=="73"){
     	                   alert(o["id"]+"-----------"+o["result"]);
     	            }*/
		         var tId = o["vaprefix"]+o["id"];
		         if(Ids["dupont"]==this.module["id"]){///
		         	var tId2 =  this.toolsMap["zcfzv"]["scode"];
		         	if(tId2==tId){
		         	   return;
		         	}
			     }
			     if(Ids["assets"]==this.module["id"]){///
			     	var tId2 =  this.toolsMap["zzcbzv"]["scode"]; 
			     	if(tId2==tId){ 	
			     		return; 		         	
			     		} 			    
			     }
			     scope.updataSpanAndProgess(o["vaprefix"]+o["id"]+"_Idspan");
		         if(this.debug)console.info(o["name"]+o["id"]+"=="+o["oldExp"]+"-->"+o["expCode"]+"-->"+o["exp"]+"=="+scope.datas[tId]);
       }catch(e){
           throw o["name"]+o["id"]+"=="+o["oldExp"]+"-->"+o["expCode"]+"-->"+o["exp"]+"=="+scope.datas[tId]+"------------------时出错了！根据程序判断【"+ o["name"]+"】不应该执行updataSpanAndProgess()这个方法的！请确认！\n"+e;
       }
    }
    /**
     * 自定义公式循环处理
     */
     this.exceteDefinedFormula=function(o){
           	   var vaprefix=o["vaprefix"],data = o["datas"];
               for(var i=0;i<scope.zIndicator.length;i++){
                  	//console.info(scope.zIndicator[i]);
                  	 var tId = scope.zIndicator[i]["scode"];
                  	  if(Ids["dupont"]==this.module["id"] && tId==this.toolsMap["qtysk"]["scope"]){
			     	 }else{
			     	 	 o["id"]="";o["result"]=0.00;
			     	      this.getDefinedIndicatorObjResult(o,scope.zIndicator[i]);
		                   scope.updataSpanAndProgess(o["id"]+"_Idspan");
                           if(this.debug)console.info(o["id"]+"-->"+o["name"]+"-->"+o["oldExp"]+"-->"+o["expCode"]+"-->"+o["exp"]+"=="+scope.datas[o["id"]]);
	
			     	    }
               }
     }
     /**
      * 处理自定义公式对象进行计算
      * DATE:20140113
      * 作者：龚佳新；
      * 改动：加了公式里有变量的处理
      */
     this.getDefinedIndicatorObjResult=function(o,bean){
     	       o["id"] = bean["scode"];bean["sname"] = bean["text"];
           	   var  exp =bean["exp"],//xx+$year$*dd/ll
           	   params = bean["params"] ;
           	   var data = o["datas"];
           	   if(exp.indexOf("$")!=-1){
           	      var expTemp  = exp.split("$");//var period = $("#year").val()+$("#month").val();
           	       var varName = expTemp[1],trueVarValue="";
           	       if(varName=="month" || varName=="year"){
           	            trueVarValue = $("#"+varName).val();
           	       }else if(varName=="company"){
           	       }
           	       exp = expTemp[0]+trueVarValue+expTemp[2];
           	   }
           	   if(params instanceof Array){
           	   }else{
           	    params = params.replaceAll("'","");
           	    params = params.replaceAll("\\)","");
           	    params = params.split(",");
//           	    console.dir(params);
           	   }
           	     for(var j=0;j<params.length;j++){
           	     	if(params[j].indexOf(o.vaprefix)==-1){
           	     	   params[j]=o.vaprefix+params[j];//a9 1 1140  11401  
           	     	}//cnbi9=250  (119+220+159) 
           	     	 var x= params[j].replaceAll("a",""),
           	           val = "data."+x,
           	        	 tempResult=eval("("+val+")");
           	        	exp = exp.replaceAll(params[j],tempResult);
           	        	//exp=(119+220+159) 
           	     }
           	     o["datas"] =  data; 
           	     o["exp"] = exp;
           	     o["name"]=bean["sname"];
           	     o["oldExp"] = bean["formula"];
           	     o["expCode"] = bean["exp"];
	             this.afterResult(o);
     }
    /**
     * 如果有行业参数
     * 处理行业参数对象
     */
    this.getNewIndustry=function(o){
    	var result={};
		 for(var key in o){
		 	var obj = o[key],vars = this.vaprefix+key, temp={};
		 	 for(var i=0;i<obj.length;i++){
		 	      temp[obj[i]["id"]] = obj[i]["scode"];
		 	 }
		 	 result[vars] =temp;
	}
	this.industyParams = result;
}
}
/**
 * author:龚佳新  
 * date:2013-11-27
 * 资产结构模型 方法全部抽取 为目前最精简模式
 */
Cnbi.model.Profita= function(params){
   //alert("Cnbi.model.Profita");
   Cnbi.model.BaseSliderAndProgress.call(this,params); 
   var  button_array = [{ renderTo : 'BQ',id:'bqId', text : "本月情况",query:3, handler : function() {updataData(this,3);}},{ renderTo : 'LJ',id:'ljId', text : "累计情况",query:4,handler : function() {updataData(this,4);} }];
   var defaults = this.defaults;
   var scope = this,domArray = params["domArray"];
   this.initPage=function(){
	      if(!scope.flag){//alert("子类的initPage");
	      		CnbiSoft.setCurrentRenderer("JavaScript");
	      		//createBtn();
	    	}

	   setFormula(false);
	   scope.setSliderValue(params.slider_array, scope.datas, "input");
	   scope.setProgressValue(params.progress_array,scope.datas, "span");
	   this.initChart(true);
	   
	   if(!scope.flag){
	        updataData();
	       }
	     	
    }
    
    function updataData(obj,a) {
    	var msg = "利润情况分析【"+scope.defaults["params"]["year"]+"---"+scope.defaults["params"]["month"]+"---"+scope.defaults["params"]["unit"]+"】";
    	if(obj){
    	  	msg+=obj.text;
    	   	//scope.defaults["params"]["query"] = a;
    	   	scope.init();
    	   	 obj.disable();
    	   	if(obj.getId()=="bqId"){
    	   	    setBtnEnable("ljId");
    	   	}else{
    	   	  	setBtnEnable("bqId");
    	   	}
    	}else{
    	  //msg+=Ext.getCmp("bqId").text;
    	  //Ext.getCmp("bqId").disable();
    	}
    }
    
    function setBtnEnable(id){
        Ext.getCmp(id).enable();
    }
    
    function createBtn() {
        for (var i = 0; i < button_array.length; i++) {
            new Ext.Button({
            	        id:button_array[i]["id"],
                        text : button_array[i]["text"],
                        renderTo : button_array[i]["renderTo"],
                        width : 100,style : {marginTop : "50px"},height : 50,
                        handler : button_array[i]["handler"]
            });
        }
    };
    this.initChart=function(action){   	  
    	  var pieChart = new Cnbi.model.Chart(getPieChartObj());
    	  pieChart.createSingleSeriesChart();
    	   var cbfyv = "cbfyvId";//params["judgeObj"]["cbfyv"];
    	  		 var obj={domId:domArray[0],datas:scope.datas[params["judgeObj"]["cbfyv"]]-0,range:scope.industyParams[cbfyv],title:'成本费用利用率'};                                                                                                                                                                                                                                                                            
    	      var angleChart = new Cnbi.model.Chart({swf:"AngularGauge",domId:cbfyv});
    	      angleChart.createAngleChart();
    	 
      	   /* if(action){ 
      		 new Cnbi.model.Chart(getAngularGaugeObj(obj));
      		  };*/
    	  }
   	  
    function getPieChartObj(){
    		var chart = {/* "yaxisname": "Quantity",
						    "xaxisname": "Fruit",*/
						    "alternatevgridcolor": "AFD8F8",
						    "basefontcolor": "114B78",
						    "tooltipbordercolor": "114B78",
						    "tooltipbgcolor": "E7EFF6",
						    "plotborderdashed": "1",
						    "plotborderdashlen": "2",
						    "plotborderdashgap": "2",
						    "useroundedges": "1",
						    "showborder": "0",
						    "bgcolor": "FFFFFF,FFFFFF"
						 };
    	return {chartType:1,//图表类型 ：0为单值数据图表;1为多单数据图表;2为多系数据图表  Pyramid
	           // datas:[{index0:"5656",index1:"",index2:""},[{index0:"2332",index1:"营业成本",index2:scope.datas[params["judgeObj"]["yycb"]]},{index0:"525",index1:"销售费用",index2:scope.datas[params["judgeObj"]["xsfy"]]},{index0:"565",index1:"财务费用",index2:scope.datas[params["judgeObj"]["cwfy"]]},{index0:"2323",index1:"管理费用",index2:scope.datas[params["judgeObj"]["glfy"]]},{index0:"8989",index1:"税金附加",index2:scope.datas[params["judgeObj"]["yysjjfj"]]}]],//显示的数据  注意：规定的数据解析格式
	            value:[125.36,80.63,70.89,56.39,63.02],
	            label:["营业成本","税金附加","销售费用","财务费用"," 管理费用","税金附加"],//销售费用  财务费用  财务费用 管理费用 税金附加
	            domId:domArray[1],//渲染的dom节点
	             color:["1C86EE","EEC900","6B8E23","9400D3","FF0000"], //颜色
	           // percent:true,
	              //chart:chart,
	             // swf:"Bar2D",//这个就不用说了吧！  //AngularGauge.swf  Pie2d Pyramid Dougnut2D
	              swf:"Pyramid",
	              chart:{bordercolor:'dddddd',showborder:0,bgcolor:'ffffff',caption:"成本费用结构图",showLabels:1,showPercentValues:1}
	           // chart:{caption:"成本费用结构图",showLabels:0,showValues:0}
	          	//attributes:'caption="成本费用结构图" formatNumberScale="0" chartTopMargin="0" chartLeftMargin="5" showBorder="1"  borderColor="dddddd"  bgColor="ffffff" bgAlpha="100" showValues="0"'
	          	}
    };	    
    var upperLimit=0.00;
    function getAngularGaugeObj(params){
     	var range = params["range"];upperLimit=range["excellent"]-0;	
     	if((params["datas"]-0)>upperLimit){
     		upperLimit = params["datas"]-0;
     	}
     
        return {chartType:0,//图表类型 ：0为单值数据图表;1为多单数据图表;2为多系数据图表
	            swf:"AngularGauge",//这个就不用说了吧！  //AngularGauge.swf
	            datas:params["datas"],//显示的数据  注意：规定的数据解析格式  numberSuffix="%"
	            domId:params["domId"],//渲染的dom节点
	            attributes:'bgAlpha="1" lowerLimit="'+range["average"]+'" upperLimit="'+upperLimit+'" lowerLimitDisplay="差" upperLimitDisplay="好" numberSuffix="%" showValue="1" palette="1" showBorder="0"',
	            color:["FF0000","EEC900","00CD00"], //颜色good 
	          	colorRange:[range["lowers"],range["average"],range["good"],upperLimit],//chartType==0时才有此属性
	          	width:"82%",height:"28%"};
    };   
    
    this.updataInputAfter=function(id ,value,datas ){		
		setFormula(true); 
	};
	
	function setFormula(action) {
		console.dir(scope.datas[params["judgeObj"]["cbfyv"]]);
		scope.initBefore();
		var  chartId=domArray[0].toString()+domArray[2].toString();
	    if(getChartFromId(chartId)){
            var tempData = scope.datas[params["judgeObj"]["cbfyv"]]-0;
	        if((scope.datas[params["judgeObj"]["cbfyv"]]-0)> upperLimit){
	    		tempData =upperLimit;
	       }
	       getChartFromId(chartId).setData(1,tempData);
	    }	       	   	      
	} 
   	scope.init();
}


